const { Add, Update, QueryOne, DelMany, Exec, Query, ExecGetOne } = require('../db/dbhelper');
var { init, format } = require('../models/dailyuser');
var { formatDateYear, formatDate } = require('../libs/common');
var _ = require('underscore');
const logger = require('../libs/log').logger;
var { matchsetFilter } = require('./matchset');
var moment = require('moment');
var { homecode } = require('../../server_config.json').wechat;
var fs = require("fs");
var path = require("path");


// 每日自动推荐用户
var dailynum = 0;
async function dailyDone(doc) {
  try {
    console.log(`-----dailyDone----开始每日推荐用户`+moment(new Date()).format("yyyy-MM-DD HH:mm:ss"));
    // 获取配置的每日推荐人数
    let setData = await QueryOne('hzz_settings', { name: '每日推荐人数' });
    dailynum = setData ? Number(setData.datastr) : 3;
    // 获取所有需要推荐的用户
    let sql_userl = `select code,grender from hzz_peoples where length(code)=12 AND online=1 AND block=0 AND level=1  `;

    if (doc && doc.code) {
      sql_userl += ` AND code='${doc.code}'`;
    }
    let userList = await Exec(sql_userl);

    // 根据用户匹配规则推荐用户，平台当日设置了置顶，则次日推送给所有用户
    logger.info(`-----dailyDone----每日推荐用户人数：`, userList.length)
    for (let index = 0; index < userList.length; index++) {
      const user = userList[index];
      let pcode = user.code;
      let mset = await matchsetFilter(pcode);
      logger.info(`-----dailyDone----每日推荐用户mset`, mset)
      let sql = `SELECT code FROM hzz_peoples WHERE isnice =0 and online=1 AND isopen=0 AND block=0 AND level=1 AND length(code)=12 AND code <>'${pcode}' AND CODE NOT IN (SELECT pcode FROM hzz_uinteresteds WHERE fcode='${pcode}') `;
      let sql_count = sql + mset.filterStr + ' ORDER BY topstate DESC,id ASC ';
      logger.info(`-----dailyDone----每日推荐用户sql_count`, sql_count)
      let peopleList = await Exec(sql_count);
      let diff = _.pluck(peopleList, 'code');
      
      if (diff.length > dailynum) {
        diff = await omitUser(pcode, diff, dailynum);//排除掉已推荐过的用户
      }
      logger.info(`-----createViterData---diff.length：${diff.length}---dailynum:${dailynum},,diff:`, diff)

      if(diff.length > dailynum){
        if (diff.length - dailynum>5) {
          diff = getRandomData(diff, dailynum);
          
        }else {
          diff = diff.splice(0, dailynum);
        }
      }
      await createDailyData(diff, pcode, dailynum);
    }
    // 推荐人复制前一天的推送取2人
    const lastDate = moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD');
    let sql_user_day = 'select code FROM hzz_peoples where length(code)=12 AND block=0 AND level=9';
    let userList2 = _.pluck(await Exec(sql_user_day), 'code');
    for (let index = 0; index < userList2.length; index++) {
      const user = userList2[index];
      let sql_user2 = `select tcode from hzz_dailyusers where builddate = '${lastDate}' AND pcode='${user}' LIMIT 0,${dailynum}; `;
      let userList3 = _.pluck(await Exec(sql_user2), 'Tcode');
      await createDailyData(userList3, user, dailynum);
    }
    console.log(`-----dailyDone----完成推荐用户`+ moment(new Date()).format("yyyy-MM-DD HH:mm:ss"));
    console.log('-----dailyDone----每日推荐用户,success')
    logger.info('-----dailyDone----每日推荐用户,success')
    if (doc && doc.code) {

    } else {
      logger.info('-----dailyDone----重置用户搜索次数--start')
      await Exec(`UPDATE hzz_matchsets SET dailytime = 0  ;`);
    }
  } catch (error) {
    console.log(`-----dailyDone----失败推荐用户`+moment(new Date()).format("yyyy-MM-DD HH:mm:ss"));
    console.log('-----dailyDone----每日推荐用户,error', error)
    logger.error('-----dailyDone----每日推荐用户,error', error)
  }
}
function getRandomData(list, num){
  try {
    var list_new = [];
    var idx=0;
    do {
      var index = Math.floor(Math.random()*list.length);
      if(index<list.length)
      {
        if(!list_new.findIndex(x=>{x== list[index]})>=0){
          list_new[idx] = list[index];
          idx++;
        }
      }
    } while (list_new.length< num);
    return list_new;
  } catch (error) {
    console.log('-----getRandomData----随机获取推荐用户,error', error)
    logger.error('-----getRandomData----随机获取推荐用户,error', error)
    return list.splice(0, num);
  }
}
// 已经推送过的先排除
var omitDay = 1;
async function omitUser(pcode, list, dailynum) {
  // 获取需要排除个数
  let outnum = list.length - dailynum;
  // 取近10日内用户已查看用户数
  const startDate = moment().subtract(10, 'day').format('YYYY-MM-DD');
  let userList = await Exec(`select * from hzz_dailyusers where pcode = '${pcode}' AND builddate> '${startDate}' ORDER BY id DESC `);
  // 依次去移除近期推荐过的
  for (let index = 0; index < userList.length; index++) {
    const user = userList[index];
    if (outnum == 0) {
      break;
    }
    if (_.contains(list, user.tcode)) {
      outnum--;
      list = _.without(list, user.tcode);
    }
  }
  return list;
  // omitDay = Math.floor(list.length/dailynum);
  // // 取近5日推荐人
  // // 最近5日日期
  // let datalist = await Exec(`SELECT DISTINCT builddate  from hzz_dailyusers  WHERE pcode='${pcode}' AND isout =1 ORDER BY createtime DESC LIMIT ${omitDay}`);
  // let old_sql = `select DISTINCT tcode from hzz_dailyusers where pcode='${pcode}' AND isout =1 AND source='每日推荐'`;
  // if(datalist.length>0){
  //   old_sql += ` AND builddate IN ('${_.compact(_.pluck(datalist, 'builddate')).join("','")}')`
  // }
  // let oldList = await Exec(old_sql);
  // let old_codes = _.compact(_.pluck(oldList,'tcode'));
  //  // 今日已推荐用户单独排除
  //  let builddate = formatDate(new Date());
  //  let todayUsers= await Exec(`select tcode from hzz_dailyusers  WHERE pcode='${pcode}' AND builddate='${builddate}'`);
  //  old_codes = _.compact(old_codes.concat(_.pluck(todayUsers,'tcode')));
  //  let diff = _.difference(list,old_codes);
  // return diff;
}
// 今日推荐不足人数的从历史中补
async function omitUserBack(pcode, list, addnum) {
  let datalist = await Exec(`SELECT DISTINCT builddate  from hzz_dailyusers  WHERE pcode='${pcode}' AND isout =1 ORDER BY id DESC LIMIT ${omitDay}`);
  let old_sql = `select DISTINCT tcode from hzz_dailyusers where pcode='${pcode}'  AND source='每日推荐'  `;
  if (datalist.length > 0) {
    old_sql += ` AND builddate NOT IN ('${_.compact(_.pluck(datalist, 'builddate')).join("','")}')    ORDER BY id ASC`
  }
  let oldList = await Exec(old_sql);
  let old_codes = _.unique(_.pluck(oldList, 'tcode'));
  let diff = _.difference(old_codes, list);
  if (diff.length >= addnum) {
    diff = list.concat(diff.splice(0, addnum));
  } else {
    diff = list.concat(diff);
  }
  return diff;
}
// 创建今日推荐用户列表
async function createDailyData(rcodes, pcode, dailynum) {
  let builddate = formatDate(new Date());
  // 当日有推荐，则清除
  await DelMany('hzz_dailyusers', { pcode: pcode, builddate: builddate });
  for (let i = 0; i < rcodes.length; i++) {
    let tcode = rcodes[i];
    if (tcode) {
      let dailyObj = {
        pcode: pcode,
        tcode: tcode,
        source: '每日推荐',
        dailynum: dailynum,
        isout: 0,
        builddate: builddate,
        createtime: new Date(),
        updatetime: new Date(),
      };
      await Add('hzz_dailyusers', dailyObj);
    }
  }
}
// 每天23:00自动清理每日推荐数据-清空10天之前的
async function clearDailyUser() {
  let leftDate = moment().subtract(2, 'day').format('YYYY-MM-DD');
  console.log('每天23:00自动清理每日推荐数据-清空11天之前的,leftDate', leftDate);
  Exec(`DELETE FROM hzz_dailyusers where builddate < '${leftDate}'`);
}
// 签到成功推送本次活动全部异性给当前用户
async function activeDone(doc) {
  try {
    let { code, activeid } = doc;
    logger.info(`-----activeDone----签到成功推送本次活动全部异性给当前用户`, doc)
    // 获取所有需要推荐的用户
    let sql_userl = `select code,grender from hzz_peoples where code='${code}'  `;
    logger.info(`-----activeDone----签到成功推送本次活动全部异性给当前用户,sql_userl`, sql_userl)
    let user = await ExecGetOne(sql_userl);
    if (user) {
      let grender = user.grender == '男' ? '女' : '男';
      // 获取本次活动异性
      let active_users = await Exec(`select pcode from  hzz_orders where activeid = ${activeid} and paystatus=1 order BY id ASC`);
      if (active_users && active_users.length) {
        let tousers = await Exec(`select code from  hzz_peoples where code IN (${_.pluck(active_users, 'pcode').join(',')}) AND grender ='${grender}'`);
        await createActiveData(_.pluck(tousers, 'code'), code,doc.activeid);
        console.log('-----activeDone----签到成功推送本次活动全部异性给当前用户,success', tousers.length)
        logger.info('-----activeDone----签到成功推送本次活动全部异性给当前用户,success', tousers.length)
      }
    }
  } catch (error) {
    console.log('-----activeDone----签到成功推送本次活动全部异性给当前用户,error', error)
    logger.error('-----activeDone----签到成功推送本次活动全部异性给当前用户,error', error)
  }
}
// 创建今日推荐用户列表
async function createActiveData(rcodes, pcode, activeid) {
  try {
    logger.info("创建今日推荐用户列表");
    let builddate = formatDate(new Date());
    // 当日有推荐，则清除
    await DelMany('hzz_dailyusers', { pcode: pcode, builddate: builddate });
    for (let i = 0; i < rcodes.length; i++) {
      let tcode = rcodes[i];
      if (tcode) {
        let dailyObj = {
          pcode: pcode,
          tcode: tcode,
          source: "活动签到",
          dailynum: 99,
          isout: 0,
          builddate: builddate,
          createtime: new Date(),
          updatetime: new Date(),
        };
        // var user = Exec(`select * from hzz_dailyusers where pcode=${pcode} and tcode=${tcode} and builddate=${builddate}`);
        // if(!user){
          await Add('hzz_dailyusers', dailyObj);
        // }
      }
    }
  } catch (error) {
    logger.info("创建今日推荐用户列表::error",error);
  }
}
// 已签到用户异性互推
async function signSendSelfUser(activeid, pcode) {
  try {
    console.log("已签到用户异性互推");
    logger.info(`-----signSendUser----已签到用户异性互推`, activeid)
    // 先推送自己
    let selfuser= await ExecGetOne(`select grender from hzz_peoples where code=${pcode}`);
    if(!selfuser)
      return;
    let grender = selfuser.grender=="男"?"女": "男";
    
    let userList = await Exec(`select * from hzz_orders where activeid = ${activeid} and signstatus = 1 and grender=${grender}`);
    logger.info(`-----signSendUser----已签到用户异性互推,已签到人数：`, userList.length);
    await createActiveData(_.pluck(userList, 'pcode'), pcode, activeid);


    userList = await Exec(`select * from hzz_orders where activeid = ${activeid} and signstatus = 1`);
    if (userList && userList.length) {
      for (let index = 0; index < userList.length; index++) {
        const user = userList[index];
        if(user.pcode == pcode)
          continue;
        // 获取本次活动已签到异性
        let users = _.filter(userList, function (x) {
          return x.grender != user.grender;
        })
        if (users && users.length > 0) {
          createActiveData(_.pluck(users, 'pcode'), user.pcode, activeid);
          logger.info('-----activeDone----签到成功推送本次活动全部异性给当前用户,success，pcode:' + user.pcode, users.length)
        }
      }
    }
  } catch (error) {
    logger.error('-----activeDone----签到成功推送本次活动全部异性给当前用户,error', error)
  }
}
async function signSendUser(activeid) {
  try {
    console.log("已签到用户异性互推");
    var flag = upFlag('read','');
    if(flag=="1"){
      logger.info(`-----signSendUser----正在异性互推，跳过`)
      return;
    }else{
      logger.info(`-----signSendUser----开始异性互推`)
      upFlag("write",'1');
      let userList = await Exec(`select * from hzz_orders where activeid = ${activeid} and signstatus = 1`);
      logger.info(`-----signSendUser----已签到用户异性互推,已签到人数：`, userList.length);
      if (userList && userList.length) {
        for (let index = 0; index < userList.length; index++) {
          const user = userList[index];
          // 获取本次活动已签到异性
          let users = _.filter(userList, function (x) {
            return x.grender != user.grender;
          })
          if (users && users.length > 0) {
            await createActiveData(_.pluck(users, 'pcode'), user.pcode);
          }
        }
      }
      logger.info(`-----signSendUser----结束异性互推`)
      upFlag("write",'0');
    }
  } catch (error) {
    logger.error('-----activeDone----签到成功推送本次活动全部异性给当前用户,error', error);

    upFlag("write",'0');
  }
}
function upFlag(type,flag){
  try {
    if(type=="read"){
      return fs.readFileSync(path.join(__dirname,'flag.txt'),'utf-8');
    }else{
      fs.writeFileSync(path.join(__dirname,'flag.txt'),flag);
    }
  } catch (error) {
    logger.error('-----upFlag----,error', error);
  }
}

async function sendhome(rcodes) {
  // 获取配置的每日推荐人数
  let setData = await QueryOne('hzz_settings', { name: '每日推荐人数' });
  dailynum = setData ? Number(setData.datastr) : 3;
  let tousers = homecode.split(',');
  for (let index = 0; index < tousers.length; index++) {
    const tocode = tousers[index];
    await createDailyData(rcodes, tocode, dailynum);
  }
  return {
    code: 0,
    msg: '发送成功，请查看'
  };
}

module.exports.dailyDone = dailyDone;
module.exports.clearDailyUser = clearDailyUser;
module.exports.activeDone = activeDone;
module.exports.signSendUser = signSendUser;
module.exports.signSendSelfUser = signSendSelfUser;
module.exports.sendhome = sendhome;
module.exports.upFlag = upFlag;